package com.sky.service.impl;

import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.sky.dto.futu.ModifyOrderRequestDto;
import com.sky.dto.futu.PlaceOrderRequestDto;
import com.sky.entity.futu.*;
import com.sky.utils.HttpUtil;
import com.sky.utils.UrlBuilder;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class FutuOrderService {

    @Value("${futu.base-url}")
    private String BASE_URL;
    private final String prefix = "/order"; // 替换为Python API的URL
    private final OkHttpClient okHttpClient;
    private final Gson gson = new Gson();

    // 拼接 BASE_URL 和 prefix
    private String getBaseUrlWithPrefix() {
        return BASE_URL + prefix;
    }

    @Autowired
    private HttpUtil httpUtil;

    @Autowired
    public FutuOrderService(OkHttpClient okHttpClient) {
        this.okHttpClient = okHttpClient;
    }

    private Object executeRequest(String url) throws IOException {
        Request request = new Request.Builder()
                .url(url)
                .build();

        try (Response response = okHttpClient.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }
            // 解析响应体为Map，具体实现可根据需要调整
            return parseResponse(response.body().string()).getData();
        }
    }

    private FutuResponse parseResponse(String responseBody) {
        return gson.fromJson(responseBody, FutuResponse.class); // 替换为实际解析
    }

    public List<Order> getHistoryOrders(String code, String start, String end) throws IOException {
        // String url = String.format(BASE_URL + "/api/order/orders?code=%s&start=%s&end=%s", code, start, end);
        String url = new UrlBuilder(getBaseUrlWithPrefix() + "/orders")
                .addParam("code", code)
                .addParam("start", start)
                .addParam("end", end)
                .build();
        return httpUtil.getList(url, Order.class);
    }

    public List<OrderFeeInfo> getOrderFee(String orderIdList) throws IOException {
        if (orderIdList == null || orderIdList.isEmpty()) {
            return new ArrayList<>();
        }
        String url = new UrlBuilder(getBaseUrlWithPrefix() + "/get_order_fee")
                // .addParam("trd_env", trdEnv)
                .addParam("order_id_list", orderIdList)
                .build();

        // Object jsonResponse = executeRequest(url);
        // log.info("jsonResponse:{}", jsonResponse);
        // return gson.fromJson(gson.toJson(jsonResponse), new TypeToken<List<OrderFeeInfo>>() {
        // }.getType());
        return httpUtil.getList(url, OrderFeeInfo.class);
    }

    /**
     * 查询未完成订单
     *
     * @param order_id
     * @param code
     * @param start
     * @param end
     * @return
     * @throws IOException
     */
    public List<OrderIncomplete> getOrderList(String order_id, String code, String start, String end) throws IOException {
        // String url = String.format(BASE_URL + "/api/order/orders?code=%s&start=%s&end=%s", code, start, end);
        String url = new UrlBuilder(getBaseUrlWithPrefix() + "/get_order_list")
                .addParam("order_id", order_id)
                .addParam("code", code)
                .addParam("start", start)
                .addParam("end", end)
                .build();
/*
        Object jsonResponse = executeRequest(url);
        log.info("jsonResponse:{}", jsonResponse);
        return gson.fromJson(gson.toJson(jsonResponse), new TypeToken<List<OrderIncomplete>>() {
        }.getType());*/
        return httpUtil.getList(url, OrderIncomplete.class);
    }


    public List<OrderPlace> placeOrder(PlaceOrderRequestDto placeOrderRequestDto) throws IOException {
        String url = new UrlBuilder(getBaseUrlWithPrefix() + "/place_order").build();
        return httpUtil.postList(url, placeOrderRequestDto, OrderPlace.class);
    }

    public List<OrderModify> modifyOrder(ModifyOrderRequestDto modifyOrderRequestDto) throws IOException {
        String url = new UrlBuilder(getBaseUrlWithPrefix() + "/modify_order").build();
        return httpUtil.postList(url, modifyOrderRequestDto, OrderModify.class);
    }
}
